#include "m_data_handle.h"
#include "stdlib.h"
#include "nrf_log.h"
#include "algo_distance.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "nrf_delay.h"
#include "player.h"
/***********************extern code*********************************/
extern bool app_get_ware_status(void);
extern bool sport_data_saved;
extern void audio_play(uint8_t voice_index); //播放音频
extern uint8_t sport_start(void);
extern void sport_end(void);
extern uint32_t ble_data_send(uint8_t* p_data, uint16_t p_length);
extern bool g_ble_running_bean_connect;
extern uint8_t bat_get_percent(void);
/*******************************************************************/
static QueueHandle_t Queue_train_msg = NULL;
static uint8_t p_sync_last_id = 0;
uint8_t test_send_data[240];
sync_cmd_t g_sync_cmd_buf = {0};

static TRAIN_EVENT_MSG m_msg={0};
bracelet_real_state_t m_bracelet_state;//课程，训练状态

uint8_t sync_flag=0;
uint8_t save_data_flag = 0;
uint8_t gps_connect_flag;

uint32_t g_sync_addr = 0xD02000;
uint32_t g_sync_total_cnt_finished = 0;

//自定义广播包
SYSTEM_INFO_T g_sysmng_info = {0};

adv_data_t g_adv_data_buf = {0};
uint16_t   g_adv_data_buf_size = sizeof(g_adv_data_buf);

ble_uart_data_t g_ble_uart_buf = {0};
uint16_t        g_ble_uart_buf_size = sizeof(g_ble_uart_buf);

ble_sync_data_t g_ble_sync_buf = {0};
uint16_t        g_ble_sync_buf_size = sizeof(g_ble_sync_buf);

char* exercise_name[] =
{
    "xxxx",
    "gbqt",
    "hdt",
    "hyp",
    "htt",
    "gtt",
    "jcb",
    "bsp",
    "kbt",
    "1000",
    "800",
    "t_1000"
};
    
void receive_cmd_handler(uint8_t* pData,uint16_t len)
{
    if(len != 5)
	{
		return;
    }
    TRAIN_EVENT_MSG msg={0};
    
    g_sync_cmd_buf.frame_head = pData[0]<<8 | pData[1];
    g_sync_cmd_buf.sync_id    = pData[2];
    g_sync_cmd_buf.total_cnt  = pData[4]<<8 | pData[3];
	if(g_sync_cmd_buf.frame_head == 0xaa01)
	{
        if(g_sync_cmd_buf.total_cnt > g_ble_uart_buf.sync_data_cnt )
        {
            return;
        }
        p_sync_last_id = g_sync_cmd_buf.sync_id;
		if(g_sync_cmd_buf.total_cnt == 0)
        {
            class_end();
        } 
        msg.u8Event = MSG_SYNC_START;
        task_train_Message_Send(msg);
	}
    else if(g_sync_cmd_buf.frame_head == 0xaa02)
	{
        if(p_sync_last_id != g_sync_cmd_buf.sync_id)
        {
            return;
        }
        else
        {
            p_sync_last_id = 0;
            g_sync_addr += sizeof(SPORT_DATA_T) * g_sync_cmd_buf.total_cnt;
            NRF_LOG_INFO("g_sync_addr=0x%x" , g_sync_addr);
            g_sync_total_cnt_finished += g_sync_cmd_buf.total_cnt;
        }         
        if(2 == m_bracelet_state.pe_state||4 == m_bracelet_state.pe_state)
        {
            msg.u8Event = MSG_SYNC_OVER;
            task_train_Message_Send(msg);
        }
	}
	return;
}

//*****************************************************************************
// * 函 数 名  : task_train_Message_Send
// * 函数功能  : 设备管理模块发送消息处理函数
// * 输入参数  :	 Message：消息
// * 输出参数  : 无
// * 返 回 值  : 无
//*****************************************************************************/
void task_train_Message_Send(TRAIN_EVENT_MSG Message)
{
    //发出消息
    if (NULL != Queue_train_msg)
    {
        xQueueSend(Queue_train_msg, &Message, 0);
    }
}

//*****************************************************************************
// * 函 数 名  : task_train_Message_SendFromISR
// * 函数功能  : 设备管理模块发送消息处理函数，从中断发送使用
// * 输入参数  :	 Message：消息
// * 输出参数  : 无
// * 返 回 值  : 无
//*****************************************************************************/
void task_train_Message_SendFromISR(TRAIN_EVENT_MSG Message)
{
    //发出消息
    if (NULL != Queue_train_msg)
    {
        xQueueSendFromISR(Queue_train_msg, &Message, 0);
    }
}

//*****************************************************************************
// * 函 数 名  : task_train_handle
// * 函数功能  : 设备管理任务处理
// * 输入参数  :	 无
// * 输出参数  : 无
// * 返 回 值  : 无
//*****************************************************************************/
void task_train_handle(void * arg)
{
    UNUSED_PARAMETER(arg);
	TRAIN_EVENT_MSG EventMsg = {0};
    Queue_train_msg = xQueueCreate(10, sizeof(EventMsg));
    while (1)
    {
        if (pdPASS == xQueueReceive(Queue_train_msg, &EventMsg, 100/portTICK_PERIOD_MS))
        {
            switch (EventMsg.u8Event)
            {
                case MSG_CLASS_START:
                {
                    class_start();
                }
                break;
                case MSG_CLASS_END:
                {
                    class_end();
                }
                break;
				case MSG_SYNC_START:
				{ 
					synchronize_data_start();
				}
				break;
				
				case MSG_SYNC_OVER:
				{
                   synchronize_data_over();
				}
				break;         
                default:
                    break;
            }
        }
        EventMsg.u8Event = 0;
    }
}
void class_start(void)
{
    g_sync_total_cnt_finished = 0;
    if (0 == m_bracelet_state.pe_state || 2 == m_bracelet_state.pe_state
        || 4 == m_bracelet_state.pe_state)//"未上课"、"上课完成"、"同步完成"状态
    {
        if (sport_start() == 0)
        {
            m_bracelet_state.pe_state = 1;//"上课中"
        }
        else
        {
            //可以放到任务中实现，pad判断上课状态
            sports_his_data_del();      //清空flash
		    m_bracelet_state.pe_state = 0;//"未上课"
		    if (sport_start() == 0)
            {
                m_bracelet_state.pe_state = 1;//"上课中"
            }
        }
        g_sync_addr = 0xD02000;
    }       
}
void class_end(void)
{
    if (m_bracelet_state.pe_state == 1)//"上课中"
	{  
		m_bracelet_state.pe_state = 2;//"上课完成待同步"
		sport_end();
	}
}
void synchronize_data_start(void)
{
    if (m_bracelet_state.pe_state == 2 || m_bracelet_state.pe_state == 4)
	{
        //等待上课数据存储完
        while (false == sport_data_saved)
        {
           nrf_delay_ms(10);
        }
        //启动同步、设置同步id、开始同步
		sync_flag  = 1;              
		m_bracelet_state.pe_state = 3; 
		sports_data_rt_upload(0);  
    }     
    else if(m_bracelet_state.pe_state == 1)
    {
        //上课期间随时同步
		sync_flag  = 1;               
		m_bracelet_state.pe_state = 3; 
        sports_data_rt_upload(0);  
        m_bracelet_state.pe_state = 1; 
    }
}
void synchronize_data_over(void)
{
    sports_his_data_del();//清空flash
    m_bracelet_state.pe_state = 0;
                    
    //开始上课
    m_msg.u8Event = MSG_CLASS_START;    
    task_train_Message_Send(m_msg);       
}
//*****************************************************************************
// * 函 数 名  : allow_sleep
// * 函数功能  : 查询是否运行休眠关机
// * 输入参数  :	 无
// * 输出参数  : 无
// * 返 回 值  : true:可以休眠关机； false:不运行休眠关机
//*****************************************************************************/
bool allow_sleep(void)
{
    //上课状态或数据同步中不做自动休眠关机
    if ((1 == m_bracelet_state.pe_state) || (3 == m_bracelet_state.pe_state))
    {
        return false;
    }
    else
    {
        return true;
    }
}

void prepare_adv_data(void)
{
    g_adv_data_buf.version = 0x10;
    g_adv_data_buf.belt_id = g_sysmng_info.belt_id;
    
    g_adv_data_buf.flag.flag_ware   = app_get_ware_status();
    g_adv_data_buf.flag.flag_RB_con = g_ble_running_bean_connect;
    g_adv_data_buf.flag.flag_GPS    = gps_connect_flag;
    
    g_adv_data_buf.bat_percent      = bat_get_percent();
    g_adv_data_buf.train_id         = m_bracelet_state.train_id;
    g_adv_data_buf.heart_rate       = g_heart_value;
    g_adv_data_buf.data_len         = sizeof(g_adv_data_buf.data);
    
    g_adv_data_buf.data.total_distance      = g_distance_total;
    g_adv_data_buf.data.total_step          = g_step_total;
    g_adv_data_buf.data.total_calorie       = g_cal_total;
    g_adv_data_buf.data.pace                = g_pace_avg;
    g_adv_data_buf.data.step_frequency      = g_step_freq_avg;
    g_adv_data_buf.data.step_length         = g_step_amplitude_avg;
    g_adv_data_buf.data.heart_rate_interval = 0;    
    g_adv_data_buf.sync_data_cnt            = g_sport_data.u32time_Sec - g_sync_total_cnt_finished;
}

void prepare_ble_uart_data(void)
{
    g_ble_uart_buf.header = 0xAAFF;
    g_ble_uart_buf.version = 0x10;
    g_ble_uart_buf.belt_id = g_sysmng_info.belt_id;

    g_ble_uart_buf.flag.flag_ware   = app_get_ware_status();
    g_ble_uart_buf.flag.flag_RB_con = g_ble_running_bean_connect;
    g_ble_uart_buf.flag.flag_GPS    = gps_connect_flag;
    
    g_ble_uart_buf.bat_percent      = bat_get_percent();
    g_ble_uart_buf.train_id         = m_bracelet_state.train_id;
    g_ble_uart_buf.heart_rate       = g_heart_value;
    g_ble_uart_buf.data_len         = sizeof(g_ble_uart_buf.data);
    
    g_ble_uart_buf.data.total_distance      = g_distance_total;
    g_ble_uart_buf.data.total_step          = g_step_total;
    g_ble_uart_buf.data.total_calorie       = g_cal_total;
    g_ble_uart_buf.data.pace                = g_pace_avg;
    g_ble_uart_buf.data.step_frequency      = g_step_freq_avg;
    g_ble_uart_buf.data.step_length         = g_step_amplitude_avg;
    g_ble_uart_buf.data.heart_rate_interval = 0;    
    g_ble_uart_buf.sync_data_cnt            = g_sport_data.u32time_Sec - g_sync_total_cnt_finished;
}
